package com.jl.encrypt;

import com.jl.encrypt.config.SecretKeyConfig;
import com.jl.encrypt.util.JLAES;
import com.jl.encrypt.util.JLRSA;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * 解密处理
 */
@Slf4j
public class JLHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers;

    private InputStream body;

    public JLHttpInputMessage(HttpInputMessage inputMessage, SecretKeyConfig.AES aes, SecretKeyConfig.RSA rsa, boolean showLog) throws Exception {
        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody;
        if (content.startsWith("{")) {
            decryptBody = content;
        } else {
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");

            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                for (String value : contents) {
                    if (aes == null) {
                        value = JLRSA.privateDecode(value, rsa.getPrivateKey());
                    } else {
                        value = JLAES.decode(value, aes.getKey());
                    }
                    json.append(value);
                }
            }
            decryptBody = json.toString();
            if (showLog) {
                log.info("原文参数：{},解密后参数：{}", content, decryptBody);
            }
        }
        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
